
function requestParamsObj_to_requestParamsString(params) {
	let s = ''
	for (let key in params) {
		s += `${key}=${params[key]}&`
	}
	s = s.slice(0, -1)
	return s
}
/**
 * @功能 ajax + promise  利用ajax 和 promise发起异步请求，返回一个promise对象，其包含请求到的xhr.responseText 转成的对象
 * @param {string} url get请求的地址
 * @param {object || string} params 查询参数
 * @param {string} paramsType
 * @param {object} headers requestHeaders
 * @param {string} dataType 数据类型
 * @returns 
 */

function axios_get(url = '', params = {}, paramsType = 'object', headers = {}, dataType = 'JSON') {
	return new Promise((resolve, reject) => {

		const xhr = new XMLHttpRequest()
		xhr.onreadystatechange = function () {
			if (xhr.readyState === 4) {
				if (xhr.status === 200) {
					let data = xhr.responseText
					switch (dataType) {
						case 'JSON': {
							data = JSON.parse(data)
							break
						}
						default: break
					}
					resolve(data)
				} else {
					reject(xhr.status)
				}
			}
		}
		//requestParams，为请求参数，利用了字符串拼接，截取
		let requestParams = ''
		if (paramsType === 'string') {
			requestParams = params
		} else {
			requestParams = requestParamsObj_to_requestParamsString(params)
		}

		xhr.open('get', `${url}?${requestParams}`)

		for (let key in headers) {
			xhr.setRequestHeader(key, headers[key])
		}

		xhr.send(null)
	})
}


function axios_post(url, params = {}, paramsType = 'object', dataSend, headers = {}) {
	return new Promise((resolve, reject) => {

		const xhr = new XMLHttpRequest()
		xhr.onreadystatechange = function () {
			if (xhr.readyState === 4) {
				if (xhr.status === 200) {
					let data = JSON.parse(xhr.responseText)
					resolve(data)
				} else {
					reject(xhr.status)
				}
			}
		}
		let requestParams = ''
		if (params === 'string') {
			requestParams = params
		} else {
			requestParams = requestParamsObj_to_requestParamsString(params)
		}
		xhr.open('post', `${url}?${requestParams}`)
		xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')
		for (let key in headers) {
			xhr.setRequestHeader(key, headers[key])
		}
		xhr.send(dataSend)
	})
}